#include <ESP8266WiFi.h>
#include <Ticker.h>
#define DebugBegin(baud_rate)    Serial.begin(baud_rate)
#define DebugPrintln(message)    Serial.println(message)
#define DebugPrint(message)    Serial.print(message)

#define AP_SSID "xiaoyou" //这里改成你的wifi名字
#define AP_PSW  "1806040103"//这里改成你的wifi密码

Ticker flipper;
const uint16_t port = 2347;
const char * host = "139.199.202.252"; // ip or dns
WiFiClient client;//创建一个tcp client连接 
int lockstatue=0;//关锁状态
void smartConfig()
{
  WiFi.mode(WIFI_STA);
  WiFi.begin(AP_SSID,AP_PSW);
   while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  DebugPrintln("");
  DebugPrintln("WiFi connected");
  DebugPrint("IP address: ");
  DebugPrintln(WiFi.localIP());
  
  //Serial.println("\r\nWait for Smartconfig");
  //delay(2000);
  // 等待配网
  //WiFi.beginSmartConfig();
// while (1)
//  {
//    //Serial.print(".");
//    delay(500);
//    if (WiFi.smartConfigDone())
//    {
//     Serial.println("SmartConfig Success");
//      Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
//      Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
//      WiFi.setAutoConnect(true);  // 设置自动连接
//      break;
//    }
//  }
// 
//  Serial.println("");
//  Serial.println("WiFi connected");  
//  Serial.println("IP address: ");
//  Serial.println(WiFi.localIP());
delay(500);
}
//每隔1s发一次消息
void senddata(){
  if(digitalRead(D4)){
      lockstatue=1;
  }else{
      lockstatue=0; 
  }
}
 
void setup()
{

     pinMode(D2, OUTPUT);
     pinMode(D4,INPUT);
     pinMode(D5, OUTPUT);//这里实际上控制的是D1
   digitalWrite(D5,LOW);
  Serial.begin(115200);
  smartConfig();
   DebugPrint("IP address: ");
  DebugPrintln(WiFi.localIP());
  client.setNoDelay(false);
  DebugPrint("connecting to ");
  DebugPrintln(host);
 flipper.attach(0.1,senddata);
 delay(500);
}
 
void loop()
{
  if(!client.connected()){
    if(!client.connect(host, port)){
        DebugPrintln("connection failed");
        DebugPrintln("wait 1 sec...");
        delay(1000);
        return;
      }
   }

    if (client.available()) {
          String data=client.readStringUntil('\r');
          DebugPrintln(data);
           if(data=="0104"){
            if(lockstatue){
                client.println(String("0113"));
            }else{
                client.println(String("0114"));
            }
          }else if(data=="0102"){//开锁命令
              lockstatue=1;
             digitalWrite(D1,HIGH);
             digitalWrite(D5,HIGH);
             client.println(String("0110")); 
             delay(1000);
             digitalWrite(D5,LOW);
          }else if(data=="0103"){//关锁
              lockstatue=0;
              digitalWrite(D2,LOW);
             digitalWrite(D5,HIGH);
             client.println(String("0111"));
             delay(1000);
             digitalWrite(D5,LOW);
          }
                 
    }

  delay(10);
}
  
